// 两数相加

function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val);
  this.next = (next === undefined ? null : next);
}

let addTwoNumbers = function (l1, l2) {
  let node = new ListNode('head');
  let temp = node;
  let add = 0;
  let sum = 0;

  while (l1 || l2) {
    sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + add;
    temp.next = new ListNode(sum % 10); // 取余数形成链表
    temp = temp.next;
    add = sum >= 10 ? 1 : 0; // 进位
    l1 && (l1 = l1.next);
    l2 && (l2 = l2.next);
  }
  if (add === 1) {
    temp.next = new ListNode(add); // 若sum大于10，将进位形成链表，放置在next上
  }
  return node.next;
};

console.log(addTwoNumbers(new ListNode(9), new ListNode(7))); 